package com.excellent.web.controller.system;

import com.excellent.common.config.ExcellentConfig;
import com.excellent.common.constant.ShiroConstants;
import com.excellent.common.core.controller.BaseController;
import com.excellent.common.core.domain.AjaxResult;
import com.excellent.common.core.domain.entity.SysMenu;
import com.excellent.common.core.domain.entity.SysRole;
import com.excellent.common.core.domain.entity.SysUser;
import com.excellent.common.core.text.Convert;
import com.excellent.common.utils.CookieUtils;
import com.excellent.common.utils.DateUtils;
import com.excellent.common.utils.ServletUtils;
import com.excellent.common.utils.ShiroUtils;
import com.excellent.common.utils.StringUtils;
import com.excellent.framework.shiro.service.SysPasswordService;
import com.excellent.system.domain.SysStuTest;
import com.excellent.system.domain.SysStuTutor;
import com.excellent.system.domain.SysUserRole;
import com.excellent.system.service.ISysConfigService;
import com.excellent.system.service.ISysMenuService;
import com.excellent.system.service.ISysRoleService;
import com.excellent.system.service.ISysStuTestService;
import com.excellent.system.service.ISysStuTutorService;
import com.excellent.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;

/**
 * 首页 业务处理
 *
 * @author excellent
 */
@Controller
public class SysIndexController extends BaseController
{
    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysStuTestService stuTestService;

    @Autowired
    private ISysStuTestService sysStuTestService;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    ISysStuTutorService sysStuTutorService;

    @Autowired
    private ISysRoleService roleService;

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", ExcellentConfig.getCopyrightYear());
        mmap.put("demoEnabled", ExcellentConfig.isDemoEnabled());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));

        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies)
        {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName()))
            {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap)
    {
        mmap.put("user", ShiroUtils.getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password)
    {
        SysUser user = ShiroUtils.getSysUser();
        if (StringUtils.isNull(user))
        {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password))
        {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin()
    {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response)
    {
        CookieUtils.setCookie(response, "nav-style", style);
    }

    // 系统首页
    @GetMapping("/system/main")
    public String main(ModelMap mmap)
    {
        return "main1";

    }
    // 流程管理
    @GetMapping("/system/process")
    public String process(ModelMap mmap)
    {
        String stage = configService.selectConfigByKey("sys.excellence.stage");
        mmap.put("stage",stage);
        return "process";

    }
    // 申请卓越班
    @GetMapping("/system/generate")
    public String generate(ModelMap mmap)
    {
        String count = configService.selectConfigByKey("sys.excellence.count");
        mmap.put("count",count);
        String firstPass = configService.selectConfigByKey("sys.excellence.firstPass");
        mmap.put("firstPass",firstPass);
        String secondPass = configService.selectConfigByKey("sys.excellence.secondPass");
        mmap.put("secondPass",secondPass);
        return "generate";

    }
    /**
     * 初次筛选
     * 选拔指定人数进入 base表。
     *
     */
    @PostMapping("/system/firstPass")
    @ResponseBody
    public AjaxResult firstPass(int firstPass){
        int count=sysStuTestService.selectCount();
        if(count>firstPass)
        {
            sysStuTestService.deleteSysStuTestFirst(count-firstPass);
            return toAjax(count-firstPass);
        }
        else{
            return toAjax(count-firstPass+1);
        }
    }
    /**
     * 初次筛选
     * 选拔指定人数进入 base表。
     *
     */
    @PostMapping("/system/secondPass")
    @ResponseBody
    public AjaxResult secondPass(int secondPass){
        int count=sysStuTestService.selectCount();
        if(count>secondPass)
        {
            sysStuTestService.deleteSysStuTestSecond(count-secondPass);
            return toAjax(count-secondPass);
        }
        else{
            return toAjax(count-secondPass+1);
        }
    }
    /**
     * 生成卓越班
     * 生成指定人数进入 tutor表 准备对接导师功能
     *
     */
    @PostMapping("/system/generate")
    @ResponseBody
    public AjaxResult generate(int count){
        List<SysStuTest> list= sysStuTestService.selectSysStuTestList(count);
        sysStuTestService.deleteSysStuTestSecond(count);

        int Scount=sysStuTestService.selectCount();
        List<SysStuTest> list1= sysStuTestService.selectSysStuTestList(Scount);
        for (int i=0;i<Scount;i++){

            SysUserRole sysUserRole =new SysUserRole();
            sysUserRole.setRoleId((long)7);
            long id= userService.selectUserByLoginName(list1.get(i).getStuSno()).getUserId();
            sysUserRole.setUserId(id);
            roleService.deleteAuthUser(sysUserRole);
        }
        int flag=0;
        SysStuTutor sysStuTutor=new SysStuTutor();
        for (int i=0;i<list.size();i++)
        {
            sysStuTutor.setStuSno(list.get(i).getStuSno());
            long id= userService.selectUserByLoginName(sysStuTutor.getStuSno()).getUserId();
            roleService.insertAuthUsers((long)8,String.valueOf(id));
            if(sysStuTutorService.insertSysStuTutor(sysStuTutor) == 1){
                ++flag;
            }
        }
        return toAjax(flag==count);
    }

    // 申请卓越班
    @GetMapping("/system/apply")
    public String apply(ModelMap mmap)
    {
        // 取身份信息
        SysUser user = ShiroUtils.getSysUser();
        String date = configService.selectConfigByKey("sys.excellence.date");
        if(user.getDeptId()==3 && date.equals(user.getLoginName().substring(0, 4)))//判断是否是目标学生
        {
            SysStuTest stuTest;
            stuTest=stuTestService.selectSysStuTestById(user.getLoginName());
            if(stuTest==null){
                mmap.put("user", user);
                return "main"; //申请页面
            }
            else{
                return "main2";//申请成功页面
            }

        }
        return "main1";

    }

    /**
     * 申请卓越班
     * 加入到sys_base
     */
    @PostMapping("/system/apply")
    @ResponseBody
    public AjaxResult apply(SysUser user1)
    {
        SysUser user=userService.selectUserById(user1.getUserId());

        if(user.getStuC()<60||user.getStuEnglish()<60||user.getStuMath()<60){
            return toAjax(-1);
        }
        List<SysRole> roles = user.getRoles();
        for(int i=0;i<roles.size();i++){
            user.setRoleId(roles.get(i).getRoleId());
        }
        user.setRoleId((long)7);
        userService.updateUser(user);
        SysStuTest stuTest=new SysStuTest();
        stuTest.setStuName(user.getUserName());
        stuTest.setStuSno(user.getLoginName());
        stuTest.setStuClass(user.getStuClass());
        stuTest.setStuC(user.getStuC());
        stuTest.setStuEnglish(user.getStuEnglish());
        stuTest.setStuMath(user.getStuMath());
        return toAjax(stuTestService.insertSysStuTest(stuTest));
    }



    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate)
    {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate)
    {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0)
        {
            if (StringUtils.isNull(pwdUpdateDate))
            {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }
}
